package com.yps.io.bio;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

import com.yps.util.Calculator;

/**
 * bio线程处理
 * @author yps
 * 用于处理一个客户端口的socket链路
 */
public class BioServerhandler implements Runnable {
	
	private Socket socket;
	public BioServerhandler(Socket socket) {
		//传参
		this.socket = socket;
	}
	
	@Override
	public void run() {
		//运行方法
		BufferedReader in = null;
		PrintWriter out = null;
		try {
			in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			out = new PrintWriter(socket.getOutputStream(),true);
			String expression;
			String result;
			while(true){//读socket
				//通过BufferedReader 读取一行
				//如果读到流尾部，返回null. 并且退出循环 
				//如果非空，在计算结果，返回值
				if((expression = in.readLine()) == null)
					break;
				System.out.println("服务端收到消息：" + expression);
				try {
					result = Calculator.cal(expression).toString();
				} catch (Exception e) {
					result = "计算错误：" + e.getMessage();
				}
				out.println(result);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			//流用完要记得关闭
			if(in != null){
				try {
					in.close();
				} catch (Exception e2) {
					e2.printStackTrace();
				}
			}
			if(out != null){
				try {
					out.close();
				} catch (Exception e2) {
					e2.printStackTrace();
				}
			}
			if(socket != null){
				try {
					socket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

}
